package com.hd.trans.ui.activity

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.common.interf.VoiceComposeListener
import com.hd.trans.databinding.ActivityTextTranResultBinding
import com.hd.trans.db.DataBaseMgr
import com.hd.trans.db.bean.FileTranslateRecord
import com.hd.trans.db.bean.HuDunLanguage
import com.hd.trans.framework.click.XClickUtil
import com.hd.trans.framework.dialog.LanguageDialog
import com.hd.trans.framework.dialog.LanguageDialogType
import com.hd.trans.framework.rom.IOUtils
import com.hd.trans.framework.tools.AppEvents
import com.hd.trans.framework.tools.HuDunEvent
import com.hd.trans.homefun.EventCode
import com.hd.trans.limit4Use.LimitUseListener
import com.hd.trans.network.PreferenceMgr
import com.hd.trans.network.component.FileTranslateManager
import com.hd.trans.network.component.TextTranslateCallback
import com.hd.trans.share.EnShareFileType
import com.hd.trans.share.ShareTextFileManager
import com.hd.trans.ui.base.LimitBaseActivity
import com.hd.trans.ui.model.PictureTransModel
import com.hd.trans.utils.Constant
import com.hd.trans.utils.StringUtils
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.TrackerForTrans
import com.hd.trans.utils.VoicePlayUtil
import com.hd.trans.widgets.VoicePlayView
import java.io.FileInputStream
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date


class TextFileTranResultActivity: LimitBaseActivity() {
    private var mCurrentViewVoice: VoicePlayView? = null
    private var isActivityPause: Boolean = false
    lateinit var voicePlayUtil: VoicePlayUtil
    lateinit var mDataBinding: ActivityTextTranResultBinding
    lateinit var mDataModel: PictureTransModel
    lateinit var fileTranslateRecord: FileTranslateRecord
    private var createTime: Long = -1L

    override fun getLayoutId(): Int {
        return R.layout.activity_text_tran_result
    }

    private val shareMG by lazy {
        ShareTextFileManager(activity)
    }

    private val fileTranslateManager by lazy {
        FileTranslateManager().apply {
            setTextTranslateCallback(object : TextTranslateCallback {
                override fun startTranslate() {
                    showLoadDialog("翻译中...")
                }

                override fun onTranslateCompleted(
                    data: String?,
                    fromLangCode: String?,
                    toLangCode: String?,
                    status: Boolean,
                )
                {
                    hideLoadDialog()
                    mDataBinding.etResult.post {
                        mDataBinding.etResult.text = data
                    }
                    fileTranslateRecord.textLanguageFrom = mDataModel.languageFrom.value
                    fileTranslateRecord.textLanguageTo = mDataModel.languageTo.value
                    DataBaseMgr.getInstance().updateFileTranslateRecord(fileTranslateRecord)

                    //保存译文到文件
                    IOUtils.write(data, FileOutputStream(fileTranslateRecord.translateText))
                }

                override fun onTranslateFailed(code: Int, msg: String?) {
                    ToastUtils.showNormal(R.string.trans_translation_failed)
                    hideLoadDialog()
                }

            })
        }
    }

    companion object {

        const val EDIT_CONTENT_CODE = 1

        @JvmStatic
        fun open(context: Context, id: Long, listener: LimitUseListener?) {
            limitListener = listener
            val intent = Intent(context, TextFileTranResultActivity::class.java)
            intent.putExtra("createTime", id)
            context.startActivity(intent)
        }
    }

    override val pageType: EventCode
        get() = EventCode.CAMERA_TRANS

    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        super.initViewsAndEvents(savedInstanceState)
        //视图埋点
        TranslationInterior.getTrackerListener().view("${TrackerForTrans.PZFY}翻译文字页面")
        createTime = intent.getLongExtra("createTime",-1L)
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_text_tran_result)
        mDataModel = ViewModelProvider(this).get(PictureTransModel::class.java)

        initView()
        initData()
    }

    override fun onResume() {
        super.onResume()
        isActivityPause = false
        //Tts语音播报插件
        voicePlayUtil = VoicePlayUtil.getInstance()
    }

    override fun onPause() {
        super.onPause()
        stopPlaying()
        voicePlayUtil.destroy()
    }

    override fun onStop() {
        super.onStop()
        isActivityPause = true
    }

    /**绑定eventbus*/
    override fun isBindEventBusHere(): Boolean {
        return true
    }

    /**通知：通知语音播放完成*/
    override fun onXEventRecv(event: HuDunEvent<*>) {
        super.onXEventRecv(event)
        when (event.eventCode) {
            AppEvents.PLAY_COMPLETE -> stopPlaying()
        }
    }
    private fun stopPlaying() {
        mCurrentViewVoice?.let {
            if(it.isPlaying()) it.stopPlay()
        }
        voicePlayUtil.stopPlay()
    }

    override fun onDestroy() {
        super.onDestroy()
        mDataModel.operateRecord.removeObservers(this)
        mDataModel.languageFrom.removeObservers(this)
        mDataModel.languageTo.removeObservers(this)
    }

    private fun initView() {
        mDataBinding.run {
            click = this@TextFileTranResultActivity
        }
    }

    private fun initData() {
        mDataModel.operateRecord.observe(this) {
            fileTranslateRecord = it
            mDataModel.languageFrom.value = it.textLanguageFrom
            mDataModel.languageTo.value = it.textLanguageTo
            val originalTextPath = fileTranslateRecord.originalText//原文内容文件路径
            val translateTextPath = fileTranslateRecord.translateText//译文内容文件路径
            try {
                val isOriginal = FileInputStream(originalTextPath)
                val isTranslate = FileInputStream(translateTextPath)
                val strOriginal: String = IOUtils.toString(isOriginal)
                val strTranslate: String = IOUtils.toString(isTranslate)
                mDataBinding.etOrigin.text = strOriginal
                mDataBinding.etResult.text = strTranslate
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        mDataModel.languageFrom.observe(this
        ) { huDunLanguage: HuDunLanguage? ->
            if (huDunLanguage != null) {
                mDataBinding.tvFrom.text = huDunLanguage.name
            }
        }
        mDataModel.languageTo.observe(this
        ) { huDunLanguage: HuDunLanguage? ->
            if (huDunLanguage != null) {
                mDataBinding.tvTo.text = huDunLanguage.name
            }
        }

        mDataModel.getFileTranslateRecordByTime(createTime)
    }

    override fun onViewClick(v: View?) {
        when(v){
            mDataBinding.btnBack -> finish()
            mDataBinding.lyFrom -> showSelectLanguageDialog(true)
            mDataBinding.lyTo -> showSelectLanguageDialog(false)
            mDataBinding.ivSwitch -> showTranslateAnimation()
            mDataBinding.btnShare -> {
                TranslationInterior.getTrackerListener()
                    .click(TrackerForTrans.PZFY, TrackerForTrans.FenXiang)
                shareTxtFile()
            }
            mDataBinding.etOrigin -> {
                TranslationInterior.getTrackerListener()
                    .click(TrackerForTrans.PZFY, TrackerForTrans.OriginalBianJi)
                EditTransResultActivity.open(this, createTime, false, EDIT_CONTENT_CODE)
            }
            mDataBinding.etResult -> {
                TranslationInterior.getTrackerListener()
                    .click(TrackerForTrans.PZFY, TrackerForTrans.TranslateBianJi)
                EditTransResultActivity.open(this, createTime, true, EDIT_CONTENT_CODE)
            }
            mDataBinding.btnCopy -> {//复制翻译结果
                val translatedText = mDataBinding.etResult.text.toString()
                if(TextUtils.isEmpty(translatedText.trim())){
                    ToastUtils.showNormal(resources.getString(R.string.tips_empty_content))
                    return
                }
                TranslationInterior.getTrackerListener()
                    .click(TrackerForTrans.PZFY, TrackerForTrans.COPY_TRANS_RESULT)
                if (!intercept()) {
                    val cmb = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                    val mClipData = ClipData.newPlainText("翻译结果", translatedText)
                    cmb.setPrimaryClip(mClipData)
                    ToastUtils.showNormal(resources.getString(R.string.copy_success_tips))
                }
            }
            mDataBinding.voicePlayView -> {
                TranslationInterior.getTrackerListener()
                    .click(TrackerForTrans.PZFY, TrackerForTrans.VOICE_PLAY)

                if (!intercept(EventCode.VOICE_PLAY_TRANS)) {
                    voicePlayback()
                }
            }
        }
    }

    /**选择语言弹框*/
    private fun showSelectLanguageDialog(isFrom: Boolean) {

        val dialog = LanguageDialog(
            mDataModel.languageFrom.value!!,
            mDataModel.languageTo.value!!,
            isFrom, LanguageDialogType.TEXT, LanguageDialogType.TO_TEXT)
        dialog.show(supportFragmentManager, "LanguageDialog")
        dialog.setOnLanguageChangedListener(object : LanguageDialog.OnLanguageChangedListener{
            override fun onLanguageChanged(
                fromLanguage: HuDunLanguage,
                toLanguage: HuDunLanguage,
                selectedLanguage: HuDunLanguage,
            ) {
                mDataModel.setLanguageFrom(fromLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveTansFromLanguage(fromLanguage.name)
                mDataModel.setLanguageTo(toLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveTansToLanguage(toLanguage.name)

                executeTrans()
            }

        })
    }

    /**执行翻译*/
    private fun executeTrans(original:String? = null) {
        if(!intercept(true)){
            stopPlaying()
            val transContentString = if(TextUtils.isEmpty(original)) mDataBinding.etOrigin.text.toString() else original
            if(TextUtils.isEmpty(transContentString?.trim())){
                ToastUtils.showNormal(resources.getString(R.string.tips_empty_content))
                return
            }
            fileTranslateManager.textTranslateQuick(
                this,
                transContentString!!,
                mDataModel.languageFrom.value?.translateCode!!,
                mDataModel.languageTo.value?.translateCode!!,
                false
            )
        }
    }

    /**
     * 语音播报
     */
    private fun voicePlayback() {
        val readContent = mDataBinding.etResult.text.toString()
        if(TextUtils.isEmpty(readContent.trim())){
            ToastUtils.showNormal(resources.getString(R.string.tips_empty_content))
            return
        }
        if (voicePlayUtil.playerImp.isPlaying) {
            voicePlayUtil.playerImp.stopPlay()
            if (mCurrentViewVoice != null && mCurrentViewVoice!!.isPlaying()) {
                mCurrentViewVoice?.stopPlay()
            }
            if (mDataBinding.voicePlayView === mCurrentViewVoice) {
                return
            }
        }
        if (mDataBinding.voicePlayView.isPlaying()) {
            mCurrentViewVoice = mDataBinding.voicePlayView
            mDataBinding.voicePlayView.stopPlay()
            return
        }

        if (mCurrentViewVoice != null && mCurrentViewVoice!!.isPlaying()) {
            mCurrentViewVoice?.stopPlay()
        }
        mCurrentViewVoice = mDataBinding.voicePlayView

        voicePlayUtil.executeCompositeFile(mDataModel.languageTo.value?.ttsCode,
            readContent,
            object : VoiceComposeListener {
                override fun onStarting() {

                    mDataBinding.voicePlayView.loading()
                }
                override fun onCompleted(file: String, isLocal: Boolean) {
                    if(isActivityPause){
                        mDataBinding.voicePlayView.stopPlay()
                    }else{
                        mDataBinding.voicePlayView.startPlay()
                        voicePlayUtil.playerImp.startPlay(file)
                    }
                }
                override fun onDownloadFailed() {
                    mDataBinding.voicePlayView.loadingFailed()
                    mDataBinding.voicePlayView.stopPlay()
                }
            })
    }

    /**
     * 互换语种动画
     */
    private fun showTranslateAnimation() {
        if ("自动检测" == mDataModel.languageFrom.value?.name) {
            return
        }
        val ta1 = TranslateAnimation(0f, (mDataBinding.lyFrom.width + mDataBinding.ivSwitch.width).toFloat(), 0f, 0f)
        ta1.duration = 600
        ta1.fillAfter = true
        mDataBinding.lyFrom.startAnimation(ta1)
        mDataBinding.lyFrom.bringToFront()
        val ta2 = TranslateAnimation(0f, (-mDataBinding.lyTo.width - mDataBinding.ivSwitch.width).toFloat(), 0f, 0f)
        ta2.duration = 600
        ta2.fillAfter = true
        mDataBinding.lyTo.startAnimation(ta2)
        mDataBinding.lyTo.bringToFront()
        ta1.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                val fromTemp: HuDunLanguage? = mDataModel.languageFrom.value
                mDataModel.setLanguageFrom(mDataModel.languageTo.value)
                mDataModel.setLanguageTo(fromTemp)
                PreferenceMgr.getInstance().translatePreference.saveFileFromLanguage(mDataModel.languageFrom.value?.name)
                PreferenceMgr.getInstance().translatePreference.saveFileToLanguage(mDataModel.languageTo.value?.name)
                animation.cancel()

                executeTrans()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        ta2.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
    }

    /**分享文本*/
    private fun shareTxtFile() {
        val originalText = mDataBinding.etOrigin.text.toString()
        val translatedText = mDataBinding.etResult.text.toString()
        if(TextUtils.isEmpty(originalText.trim())
            && TextUtils.isEmpty(translatedText.trim())){
            ToastUtils.showNormal(resources.getString(R.string.tips_empty_content))
            return
        }
        shareMG.shareTextFile(
            StringUtils.template(originalText, translatedText),
            shareFileName(),
            EnShareFileType.TXT_FILE
        )
    }

    private fun shareFileName(): String? {
        val mFormat = SimpleDateFormat("yyyyMMdd_HHmmss")
        return mFormat.format(Date().time)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode== EDIT_CONTENT_CODE) {//是否选择，没选择就不会继续
            data?.let {
                val result = data.getStringExtra(Constant.EDIT_CONTENT_RESULT)
                val isTransPart = data.getBooleanExtra(Constant.EDIT_CONTENT_TYPE, false)
                if(isTransPart){
                    mDataBinding.etResult.text = result

                    IOUtils.write(result, FileOutputStream(fileTranslateRecord.translateText))
                } else {
                    mDataBinding.etOrigin.text = result
                    IOUtils.write(result, FileOutputStream(fileTranslateRecord.originalText))
                    executeTrans()
                }
                ToastUtils.showNormal("已保存")
            }
        }
    }
}